package frames;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JFrame;


/**
 * The <code>TableRecordsFrame<code> populates the <code>JTable<code> with the database's data.
 * 
 * @author Mariya Valcheva
 * @version 1.0
 * 
 */
@SuppressWarnings("serial")
public class TableRecordsFrame extends JFrame{
	
	/* Parameters from constructor */ 
	private Connection connection;
	private String databaseName;
	private String tableName;
	
	/* Table data */  
	private String[] columnNames;
	private String[][] tableData;
	
	/* Additional variables */ 
	private int numberOfRows = 0;
	private int numberOfColumns = 0;
	
	private JScrollPane jRecordsTableSP;
    private JTable jRecordsTable;

    /**
     * Sets the connection, database name and table name.
     * @param conn the connection.
     * @param dbName the database name.
     * @param tblName the table name.
     * @throws SQLException if the connection is not successful.
     */
	public TableRecordsFrame(final Connection conn, 
							 final String dbName, 
							 final String tblName) throws SQLException{ 
		super("Records (" + tblName + ")");
		connection = conn;
		databaseName = dbName;
		tableName = tblName;		
	}
	
	/**
	 * Shows the table records in a <code>JTable<code>.	
	 * @throws SQLException
	 */
	public void showTableRecords() throws SQLException{
		getTableComponents();
		initComponents();
		this.setVisible(true);
	}

	/**
	 * Gets the table components. The <code>ResultSet<code> is scrollable and modifiable.The first index of 
	 * the <code>ResultSet<code> is 1.
	 * @throws SQLException if the connection is not successful.
	 */
	private void getTableComponents() throws SQLException{
		Statement stmt = null;
	    String query = "select * from " + databaseName + "." + tableName;

	    try {	    	
	        stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                                              ResultSet.CONCUR_UPDATABLE);
	        ResultSet rs = stmt.executeQuery(query);
	        ResultSetMetaData rsmd = rs.getMetaData();
	        
	        numberOfColumns = rsmd.getColumnCount();
	        columnNames = new String[numberOfColumns];
	        
	        if(!rs.last()) return;
	        numberOfRows = rs.getRow();
	        tableData = new String[numberOfRows][numberOfColumns];
	        rs.first();
	        
	        for(int k = 0; k < numberOfColumns; k++){  
            	columnNames[k] = rsmd.getColumnName(k + 1); //retrieves all columns' names;
            }
	        
	        int x = 0; 	        
	        do {  //iterates on resultset's rows;	        	
	            for(int y = 0; y < numberOfColumns; y++){  //gets row's data;	            	
	            	tableData[x][y] = rs.getString(y+1);
	            }
	            
	            x++;
	        } while (rs.next());
	    } catch (SQLException ex) {
	    	JOptionPane.showMessageDialog(null, ex.getMessage());
	    } finally {
	        if (stmt != null) { stmt.close(); }
	    }		
	}
	
	/**
	 * Initializes the get table data in the <code>JTable<code>.
	 */
	private void initComponents(){
		jRecordsTableSP = new JScrollPane();
        jRecordsTable = new JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
        jRecordsTable.setModel(new javax.swing.table.DefaultTableModel(tableData, columnNames));
        
        jRecordsTableSP.setViewportView(jRecordsTable);

        javax.swing.GroupLayout paneLayout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(paneLayout);
        paneLayout.setHorizontalGroup(
            paneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jRecordsTableSP, javax.swing.GroupLayout.DEFAULT_SIZE, 655, Short.MAX_VALUE)
        );
        paneLayout.setVerticalGroup(
            paneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jRecordsTableSP, javax.swing.GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE)
        );

        pack();
	}
}
